import 'dart:math';

import 'package:huxiaodui/api/api.dart';
import 'package:huxiaodui/api/model/notice_model.dart';
import 'package:huxiaodui/components/keep_alive_wrapper.dart';
import 'package:huxiaodui/components/gallery.dart';
import 'package:huxiaodui/components/VideoPlayerApp.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

enum FileType {
  image,
  video,
  other,
}

FileType getFileType(String filePath) {
  String extension = filePath.split('.').last.toLowerCase();
  if (extension == 'jpg' ||
      extension == 'jpeg' ||
      extension == 'png' ||
      extension == 'gif') {
    return FileType.image;
  } else if (extension == 'mp4' ||
      extension == 'mov' ||
      extension == 'avi' ||
      extension == 'mkv') {
    return FileType.video;
  } else {
    return FileType.other;
  }
}

class MyNoticePage extends StatefulWidget {
  const MyNoticePage({super.key});
  @override
  State<MyNoticePage> createState() => _MyNoticePageState();
}

class _MyNoticePageState extends State<MyNoticePage> {
  List<NoticeModel> notices = [NoticeModel.fromJson({})];
  ScrollController controller = ScrollController();

  int size = 10;
  int page = 0;

  @override
  void initState() {
    super.initState();
    Api.request(
      isToast: true,
      url: NoticeUrl.all,
      data: {"page": page, "size": size},
      success: (res) {
        notices = NoticeModel.toList(res.data);
        page++;
        setState(() {});
      },
    );

    controller.addListener(() {
      if (controller.position.pixels == controller.position.maxScrollExtent) {
        Api.request(
          url: NoticeUrl.all,
          data: {"page": page, "size": size},
          success: (res) {
            notices.addAll(NoticeModel.toList(res.data));
            page++;
            setState(() {});
          },
        );
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("我的消息"),
      ),
      body: ListView.builder(
        controller: controller,
        itemCount: notices.length,
        itemBuilder: (BuildContext context, int index) {
          var controller = TextEditingController();
          controller.text = notices[index].body;

          List<GalleryItem> galleryItems = [];
          List<Widget> videos = [];
          if (notices[index].fileUrls.isNotEmpty) {
            for (int id = 0; id < notices[index].fileUrls.length; id++) {
              var url = notices[index].fileUrls[id];
              var type = getFileType(url);
              if (type == FileType.image) {
                galleryItems.add(
                  GalleryItem(
                    id: Random(10),
                    resource: Image.network(url, //${config.host}/image/$element
                        width: 200,
                        height: 200,
                        fit: BoxFit.cover),
                  ),
                );
              } else if (type == FileType.video) {
                videos.add(
                  VideoPlayerScreen(
                    url: url,
                    onState: (res) {
                      setState(() {});
                    },
                  ),
                );
                videos.add(Container(height: 1));
              }
            }
          }

          return KeepAliveWrapper(
            child: Container(
              padding:
                  const EdgeInsets.only(top: 8, bottom: 5, left: 8, right: 8),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Container(
                        padding: const EdgeInsets.only(left: 5, right: 10),
                        child: Text(
                          notices[index].title,
                          textAlign: TextAlign.left,
                          maxLines: null,
                          style: const TextStyle(fontSize: 16),
                        ),
                      ),
                      Text(
                        notices[index]
                            .createdAt
                            .toIso8601String()
                            .split('.')[0]
                            .replaceAll('T', ' '),
                        style:
                            const TextStyle(fontSize: 12, color: Colors.grey),
                      ),
                    ],
                  ),
                  Container(
                    padding: EdgeInsets.all(5),
                    child: Text(
                      notices[index].body,
                      textAlign: TextAlign.left,
                      maxLines: null,
                    ),
                  ),
                  Visibility(
                    visible: galleryItems.isNotEmpty,
                    child: SizedBox(
                      child: GalleryComponents(
                        galleryItems: galleryItems,
                      ),
                    ),
                  ),
                  Column(children: videos),
                  const Divider(
                    color: Colors.grey,
                    thickness: 1.0,
                  ),
                ],
              ),
            ),
          );
        },
      ),
    );
  }
}
